<?php
namespace app\common\model\logic;

use app\common\model\WechatModel;
use think\Db;
use think\exception\DbException;
use think\Model;

class CarOrderModel extends Model {

    protected $name = 'car_order'; //定义栏目表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = true;
    //类型自动转换
    protected $type = [
        'order_start_time'=>'timestamp:Y-m-d H:i:s',
        'order_end_time'=>'timestamp:Y-m-d H:i:s',
        'out_time'=>'timestamp:Y-m-d H:i:s',
        'begin_time'=>'timestamp:Y-m-d H:i:s',
        'back_time'=>'timestamp:Y-m-d H:i:s',
        'order_start_mm'=>'integer',
        'order_end_mm'=>'integer',
        'order_mileage'=>'integer',
        'order_charge'=>'float',
        'order_advance'=>'float',
        'sort'=>'integer',
        'short_info'=>'array'
    ];
    public function getCarStatusTextAttr($value, $data)
    {
        $arr=['1'=>'出车','2'=>'收车'];
        return $arr[$data['car_status']];
    }
    public function getIsPushTextAttr($value, $data)
    {
        $arr=['1'=>'否','2'=>'是'];
        return $arr[$data['is_push']];
    }


    /**
     * 获取检索条件
     * @param $query
     */
    public function getExtendMap($query){
        $map=[];
        if(!empty($query['car_sn'])){
            $map['car_sn'] = ['like','%'.$query['car_sn'].'%'];
        }
        if($query['car_status']>-1 && $query['car_status']<4){
            $map['car_status'] = ['in',$query['car_status']];
        }
        if($query['car_status']==4){
            $map['order_q'] = ['>',0];
        }
        if(!empty($query['fleet_driver'])){
            $map['fleet_driver'] = ['like','%'.$query['fleet_driver'].'%'];
        }
        if($query['short_status']==1){
            $map['short_price'] = 0;
        }
        if(!empty($query['order_start_adress'])){
            $map['order_start_adress'] = ['like','%'.$query['order_start_adress'].'%'];
        }
        if(!empty($query['order_end_adress'])){
            $map['order_end_adress'] = ['like','%'.$query['order_end_adress'].'%'];
        }
        if(!empty($query['rangdate'])){
            $rangTime = explode('~',$query['rangdate']);
            $map['order_start_time'] = ['between',[strtotime($rangTime[0].' 0:00:00'),strtotime($rangTime[1].' 0:00:00')]];
        }
        if($query['btype_id']>0){
            $map['btype_id'] = $query['btype_id'];
        }
        return $map;
    }

    //读取单条数据
    public function read($aid){
        try{
            $info = $this->get($aid)->toArray();
            $info = $this->formatInfo($info);
            return $info;
        } catch (\Exception $e){
            exception($e->getMessage(),40001);
        }
    }

    //格式化列表
    public function formatList($list){
        $carLeaveModel = new CarLeaveModel();
        $leaveUids = $carLeaveModel->where('last_time>0')->where('leave_end_time','>',time())->column('leave_uid'); //请假异常的司机绑定UID
        $driverIds=0;
        if($leaveUids){
            $carDriverModel = new CarDriverModel();
            $driverIds = $carDriverModel->where('bind_uid','in',$leaveUids)->column('aid'); //异常司机ID
        }
        foreach($list as $k=>$v){
            $list[$k]['no_dri_ids'] = $driverIds;
            $list[$k]['action_name'] = get_field_value('user','name',['uid'=>$v['uid']]);
            $list[$k]['order_pay_list'] = Db::table('car_order_pay')->where('order_id',$v['aid'])->select();
        }
        return $list;
    }
    //格式化单条内容
    public function formatInfo($info){
        try {
            $info['btype_out'] = CarBtypeModel::get($info['btype_aid'])->toArray();
        } catch (\Exception $e) {
            $info['err'] = $e->getMessage();
        }
        return $info;
    }

    //添加数据
    public function add($data){
        try{
            $cars = explode(',',$data['car_sn']);
            //订单批号
            $data['order_odd'] = rand_number();
            //客户
            if($data['is_customer_add']){ //新增客户
                $carBtypeModel = new CarBtypeModel();
                $cData=[
                    'title'=>$data['order_client'],
                    'btype_phone'=>$data['order_phone'],
                ];
                $carBtypeModel->isUpdate(false)->allowField(true)->save($cData);
                $data['btype_id']=$carBtypeModel->getData('aid');
            }
            $dataList = [];
            foreach($cars as $car_sn){
                //1 判断上一笔订单是否已收车
                $lastorder = $this->where('car_sn',$car_sn)->order('aid desc')->find();
                if($lastorder){ //有上一笔订单
                    //0未指派 1已指派 2出发中 3已收车
                    if($lastorder['car_status']==3){ //收车
                        $data['sum_odd'] = $car_sn.'-'.date('YmdHi'); //新结算单
                    }else{
                        $data['sum_odd'] = $lastorder['sum_odd'];//旧结算单
                    }
                }else{
                    $data['sum_odd'] = $car_sn.'-'.date('YmdHi');
                }
                $data['title'] = $data['order_client'].'['.$data['order_start_adress'].'-'.$data['order_end_adress'].']行程单';
                $data['car_sn'] = $car_sn;
                $dataList[]=$data;
            }
            $this->allowField(true)->saveAll($dataList,false);
            return true;
        }catch (\Exception $e){
            exception($e->getMessage(),40001);
        }
    }
    //修改数据
    public function edit($data){
        try{
            if($data['car_status']==2){ //收车同步更新车辆状态
                $carModel = new CarModel();
                $carModel->where('	car_sn',$data['car_sn'])->update(['car_status'=>0]);
                $data['back_time']=date('Y-m-d H:i:s'); //更新收车时间
            }
            $data['title'] = $data['order_client'].'['.$data['order_start_adress'].'-'.$data['order_end_adress'].']行程单';
            $this->isUpdate(true)->allowField(true)->save($data);
            return true;
        } catch (\Exception $e){
            exception($e->getMessage(),40001);
        }
    }

    //删除数据
    public function del($aid){
        try{
            $this->destroy($aid);
            Db::table('car_order_pay')->where('order_id',$aid)->delete();
            return true;
        } catch (\Exception $e){
            exception($e->getMessage(),40001);
        }
    }
    //行程单
    public function spend($aid){
        $orderInfo = Db::table('car_order')->where('aid', $aid)->find(); //订单信息
        $carInfo = Db::table('car')->where('car_sn', $orderInfo['car_sn'])->find(); //车辆信息
        $driver = Db::table('car_driver')->where('aid', 'in', $orderInfo['fleet_driver_ids'])->column('title,dri_phone'); //司机信息
        $days = '未生成';
        if ($orderInfo['car_status'] == 2) { //收车
            $days = ($orderInfo['order_end_time'] - $orderInfo['order_start_time']) / 86400;
        }
        $data = [
            'car_sn' => $orderInfo['car_sn'], //车号
            'seat' => $carInfo['car_seat'], //座位数
            'driver' => $driver, //司机信息
            'order_company' => $orderInfo['order_company'], //客户单位
            'order_client' => $orderInfo['order_client'], //客户姓名
            'order_phone' => $orderInfo['order_phone'], //客户电话
            'guide' => $orderInfo['guide'], //导游姓名
            'guide_tel' => $orderInfo['guide_tel'], //导游电话
            'order_start_time' => date('Y-m-d H:i', $orderInfo['order_start_time']), //开始日期
            'order_end_time' => date('Y-m-d H:i', $orderInfo['order_end_time']), //结束日期
            'begin_time' => date('Y-m-d H:i', $orderInfo['begin_time']), //接团时间
            'order_start_adress' => $orderInfo['order_start_adress'], //接团地点
            'order_desc' => $orderInfo['order_desc'], //行程路线
            'diff_days' => $days, //天数

            //客户相关费用
            'order_charge' => $orderInfo['order_charge'], //车费 订单费用
            'order_advance' => $orderInfo['order_advance'], //定金
            'order_pay_type' => $orderInfo['order_pay_type'], //结算方式 //现金 转账  vachar
            'order_pay' => $orderInfo['order_pay'], //已收费金额
            'order_q' => $orderInfo['order_charge'] - $orderInfo['order_pay'], //代收款
            //司机相关费用
            'order_service' => $orderInfo['order_service'], //服务费
            'order_tolls' => $orderInfo['order_tolls'], //过路费
            'order_stop' => $orderInfo['order_stop'], //停车费
            'order_fuel' => $orderInfo['order_fuel'], //加油费
            'order_l' => $orderInfo['order_l'], //加油升数
            'order_eat' => $orderInfo['order_eat'], //食宿
            'order_other' => $orderInfo['order_other'], //其他
            'order_bala' => $orderInfo['order_other'], //结余

        ];
        return $data;
    }
}